package com.example.mytips.findWidget;

import com.example.mytips.structure.ClassEntity;
import com.example.mytips.structure.FlutterStructureDialog;
import com.example.mytips.utils.DialogUtils;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import org.apache.http.util.TextUtils;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FindWidget extends AnAction {

    private List<FindWidgetEntity> list;

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        list = new ArrayList<>();
        ///当前工程
        Project project = e.getProject();

        String projectPath = project.getBasePath();

        ///上下文
        DataContext context = e.getDataContext();

        String lib = projectPath + "/lib";
        //String ExampleLib = projectPath + "/example/lib";


        // 获取目录的虚拟文件对象
        VirtualFile baseDir = LocalFileSystem.getInstance().findFileByPath(lib);
        if (baseDir != null && baseDir.isDirectory()) {
            // 遍历目录的所有子目录和文件
            traverseDirectory(project, baseDir);
        }

        System.out.println(list);
        if (list.size() == 0) return;

        FlutterWidgetDialog dialogWrapper = new FlutterWidgetDialog(e, list);
        DialogUtils.screenCenterShow(dialogWrapper);
        dialogWrapper.show();


    }

    ///遍历目录下所有的子目录
    private void traverseDirectory(@NotNull Project project, @NotNull VirtualFile directory) {
        for (VirtualFile file : directory.getChildren()) {
            // 检查文件是否是一个目录
            if (file.isDirectory()) {
                // 递归遍历子目录
                traverseDirectory(project, file);
            } else {
                // 检查文件是否以.dart结尾
                if (file.getName().endsWith(".dart")) {
                    System.out.println("全路径：" + file.getUrl());

                    List<String> stringList = getContentByPath(file);

                    for (int i=0;i<stringList.size();i++) {
                        String lineStr = stringList.get(i);

                        String trim = lineStr.trim();
                        if (trim.startsWith("//mark")) {

                            ///取值
                            List<String> strings = Arrays.stream(trim.split(":")).toList();
                            String groupName = getLineStrByList(1, strings);
                            String note = getLineStrByList(2, strings);

                            ///有可能是接下来是空行
                            int lineNum = i + 1;
                            String lineString = getLineStrByList(lineNum, stringList);
                            if (TextUtils.isEmpty(lineString)) {
                                lineNum = i + 2;
                                lineString = getLineStrByList(lineNum, stringList);
                            }

                            if (!TextUtils.isEmpty(lineString)) {
                                ClassEntity classEntity = isClass(lineString, lineNum);

                                if (classEntity != null && !TextUtils.isEmpty(groupName)) {
                                    FindWidgetEntity entity = new FindWidgetEntity();
                                    entity.path = file.getPath();
                                    entity.groupName = groupName;
                                    entity.note = note;
                                    entity.className = classEntity.name;
                                    entity.line = classEntity.startLineNum;

                                    list.add(entity);
                                }
                            }

                        }
                    }


                }
            }
        }
    }

    /**
     * 是否是类
     */
    ClassEntity isClass(String lineStr, int line) {
        if (TextUtils.isEmpty(lineStr)) return null;

        String classStart = "class ";
        String abstractClassStart = "abstract class ";
        String extensionStart = "extension ";
        String enumStart = "enum ";

        boolean isClassStart = lineStr.startsWith(classStart);
        boolean isAbstractClassStart = lineStr.startsWith(abstractClassStart);
        boolean isExtensionStart = lineStr.startsWith(extensionStart);
        boolean isEnumStart = lineStr.startsWith(enumStart);

        if (isClassStart || isAbstractClassStart || isExtensionStart || isEnumStart) {

            //取出类名
            String className = "";
            String newLineStr = lineStr;
            if (isClassStart) {
                newLineStr = newLineStr.substring(classStart.length());
            } else if (isAbstractClassStart) {
                newLineStr = newLineStr.substring(abstractClassStart.length());
            } else if (isExtensionStart) {
                newLineStr = newLineStr.substring(extensionStart.length());
            } else if (isEnumStart) {
                newLineStr = newLineStr.substring(enumStart.length());
            }

            String[] splitList = newLineStr.split(" ");
            className = splitList[0];
            className = className.replace("{","");
            className = className.replace("}","");

            ClassEntity classEntity = new ClassEntity();
            classEntity.startLineNum = line;
            classEntity.name = className.trim();

            String[] split = lineStr.split(classEntity.name);
            if (split.length > 0) {
                classEntity.type = split[0].trim();
            }
            return classEntity;
        }

        return null;
    }

    ///取出一行
    private String getLineStrByList(int index,List<String> list) {
        if (list == null) return "";
        if (index >= list.size()) return "";
        return list.get(index);
    }

    ///读取文件
    private List<String> getContentByPath(VirtualFile psiFile){
        // 一行一行读取文件
        List<String> lineList = new ArrayList<>();
        //StringBuilder stringBuilder = new StringBuilder();
        try {
            assert psiFile != null;
            try (InputStream inputStream = psiFile.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    // 在这里处理每一行的内容
                    lineList.add(line);
                    //stringBuilder.append(line);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return lineList;
    }
}


